package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"melon/server/constant"
	"melon/server/global"
	"melon/server/model"
	"melon/server/utils/response"
	"net/http"
	"net/url"
)

type Version struct {
}

func (v *Version) Update(context *gin.Context) {
	var req model.VersionRequest
	// 绑定参数
	if err := context.ShouldBindJSON(&req); err != nil {
		response.Fail(context, constant.ValidatorParamsCheckFailCode, constant.ValidatorParamsCheckFailMsg, "")
	}

	myClient := &http.Client{}
	for _, value := range req.Req {
		urlString := global.MelonYml.GetString("HttpClient.Url")
		request, _ := http.NewRequest("GET", encodeUrl(urlString, value.Key, value.Value), nil)
		resp, _ := myClient.Do(request)
		s, err := ioutil.ReadAll(resp.Body)
		var a model.VersionResponse
		if err = json.Unmarshal(s, &a); err != nil {
			response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
			return
		}
		if a.Code != "0" {
			response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
			return
		}
	}
	response.Success(context, constant.CurdStatusOkMsg, "")
}

func encodeUrl(baseUrl, key, value string) string {
	params := url.Values{}

	Url, err := url.Parse(baseUrl)
	if err != nil {
		panic(err.Error())
	}
	params.Set("key", key)
	params.Set("val", value)
	Url.RawQuery = params.Encode()
	return Url.String()
}
